package cn.wangxl.vertx.starter.web;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;

/**
 * 重新路由:
 * 可以用于适当情况下的重路由：
 *  查询用户为空，返回404
 *
 */
public class ReRouteVerticle extends AbstractVerticle {

  @Override
  public void start(Future<Void> startFuture) throws Exception {
    Vertx vertx = Vertx.vertx();
    HttpServer server = vertx.createHttpServer();

    Router router = Router.router(vertx);

    router.get("/test1").handler(ctx->{

      System.out.println("第一个路由/test1");

      ctx.reroute("/test2");
    });
    router.route("/test2").handler(ctx->{
      System.out.println("重路由/test2");
      ctx.response().end();
    });

    router.get("/user").handler(ctx->{
      System.out.println("查询用户信息为空");
      ctx.response().setStatusCode(404);
      ctx.reroute("/notfound");
    });
    router.route("/notfound").handler(ctx->{
      if(ctx.response().getStatusCode() == 404){
        System.out.println("上级路由失败，返回404");
      }
      ctx.response().end();
    });

    server.requestHandler(router).listen(8888, http -> {
      if (http.succeeded()) {
        startFuture.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startFuture.fail(http.cause());
      }
    });
  }


  public static void main(String[] args) throws Exception {
    new ReRouteVerticle().start(Future.future());
  }
}
